package com.zyf.concurrency.chapter14;

import com.zyf.concurrency.annotations.GuardedBy;
import com.zyf.concurrency.annotations.ThreadSafe;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用lock来实现信号量
 * (Not really how java.util.concurrent.Semaphore is implemented)
 * create by yifeng
 */
@ThreadSafe
public class SemaphoreOnLock {
    private final Lock lock = new ReentrantLock();
    // CONDITION PREDICATE: permitsAvailable (permits > 0)
    private final Condition permitsAvailable = lock.newCondition();
    // 许可证,线程安全的，被锁-Lock
    @GuardedBy("lock")
    private int permits;

    public SemaphoreOnLock(int initialPermits) {
        lock.lock();
        try {
            this.permits = initialPermits;
        } finally {
            lock.unlock();
        }
    }

    // Blocks-until ： permitsAvailable
    public void acquire() throws InterruptedException {
        lock.lock();
        try {
            while (permits <= 0)
                // 等待许可
                permitsAvailable.await();
        } finally {
            lock.unlock();
        }
    }
    // 释放许可
    public void release() {
        lock.lock();
        try {
            ++permits;
            // 通知
            permitsAvailable.signal();
        } finally {
            lock.unlock();
        }
    }
}
